import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { config } from '../smartadmin.config'
import { Router } from '@angular/router'

declare var $: any
var pinyin = require('pinyin')
@Component({
  selector: 'sa-company-tree',
  templateUrl: './companyTree.component.html',
  styleUrls: ['./companyTree.component.css']
})
export class CompanyTreeComponent implements OnInit {
  @Input() companyTreeId: string //公司树标识Id
  @Input() wrap: any //事件页面根元素
  @Input() wrapId: any //事件页面根元素Id
  @Input() companyData: any //父组件公司数据
  @Input() companyNameValue: string //绑定公司name
  @Input() companyIdValue: string //绑定公司Id
  @Input() root: boolean = false //根目录(默认隐藏)
  @Input() Height: number //高度
  @Input() disabled: false //禁用输入框
  @Input() inputName: string = 'companyName' //校验使用的公司名称;默认name="companyName"
  @Input() placeholder: string = '请选择' //弱提示语
  @Input() inputParam: any = {} //接口参数
  @Input() inputApi: string = 'company/companytree.html' //接口参数
  @Input() companyParentList: any //父级公司数据
  @Input() companyListName: any = 'ROOT(根目录)' //父级公司数据
  @Output() companySelected = new EventEmitter()
  private companyName: string = '' //选中的公司名称
  private companyId: string = '' //选中的公司ID
  private companyCode: string = '' //选中的公司code
  private companyOption: any = {} //选中的公司选项
  private compantList: any = [] //公司数据
  selectIndex: any = '' // 选中的位置
  selectCount: any = '' // 选中的总数
  clearTimer: any = '' // 定时器id
  constructor(private jsonApiService: JsonApiService, private el: ElementRef, private router: Router) {}
  //传参给父组件
  sendParent() {
    let companyInfo = {
      companyName: this.companyName,
      companyId: this.companyId,
      companyCode: this.companyCode,
      companyList: this.compantList,
      companyOption: this.companyOption
    }
    this.companySelected.emit(companyInfo)
  }
  ngOnInit() {
    System.import('assets/js/jstree/jstree.min.js').then(() => {
      this.initCompanyList()
      this.companyCilckEvent()
    })
  }
  ngOnChanges() {
    if (this.companyIdValue && this.companyNameValue) {
      this.companyId = this.companyIdValue
      this.companyName = this.companyNameValue
      $('#' + this.companyTreeId)
        .find('.tree_company_input')
        .val(this.companyName)
        .change()
      //		    this.sendParent();
    }
  }
  //页面点击事件监听
  companyCilckEvent() {
    let companyTreeM = document.getElementById(this.companyTreeId)
    let tree_box = companyTreeM.getElementsByClassName('s_tree_box')[0]
    let company = companyTreeM.getElementsByClassName('tree_company_input')[0]
    let wrap
    if (this.wrapId) {
      wrap = document.getElementById(this.wrapId)
    } else {
      if (this.wrap == 'body') {
        wrap = document.getElementsByTagName('body')[0]
      } else if (this.wrap == 'html') {
        wrap = document.getElementsByTagName('html')[0]
      } else {
        wrap = document
      }
    }
    wrap.onclick = null
    wrap.onclick = function (e: any) {
      if (tree_box.contains(e.target) || e.target == company) {
        //判断点击是否在下拉框内
        if (
          e.target.className == 'jstree-anchor jstree-hovered jstree-clicked' ||
          e.target.className == 'jstree-icon jstree-themeicon fa fa-home jstree-themeicon-custom' ||
          e.target.className == 's_company_root' ||
          e.target.className == 'jstree-anchor jstree-hovered jstree-clicked jstree-search jstree-searchCheck'
        ) {
          tree_box.className = tree_box.className.replace('tree_open', '')
        }
      } else {
        tree_box.className = tree_box.className.replace('tree_open', '')
        $('#' + this.companyTreeId)
          .find('.treeSearchInput')
          .val('')
      }
    }.bind(this)
  }
  ngOnDestroy() {
    let wrap: any = this.wrapId
      ? document.getElementById(this.wrapId)
      : this.wrap
      ? document.getElementsByTagName(this.wrap)
      : document
    wrap.onclick = null
  }
  //拉取公司数据,生成树形图
  initCompanyList() {
    // 销毁 jsTree
    $('#' + this.companyTreeId)
      .find('.treeId')
      .eq(0)
      .jstree('destroy')
    var that = this
    $('#' + this.companyTreeId)
      .find('.treeId')
      .eq(0)
      .data('jstree', false)
      .empty()
      .jstree({
        core: {
          data: function (obj, callback) {
            var jsonstr = '[]'
            var jsonarray = eval('(' + jsonstr + ')')
            // if(that.companyParentList == undefined || that.companyParentList.length == 0){
            $.ajax({
              type: 'POST',
              url: config.BaseURL + that.inputApi,
              dataType: 'json',
              cache: false,
              xhrFields: {
                withCredentials: true
              },
              timeout: 30000,
              data: that.inputParam,
              success: function (result) {
                // 增加公司拼音字段
                var forData = result.data ? result.data : result
                if (forData.length) {
                  for (let i = 0; i < forData.length; i++) {
                    forData[i].text =
                      forData[i].text +
                      `<span style="display: none;">${pinyin(forData[i].text, { style: pinyin.STYLE_NORMAL }).join(
                        ''
                      )}</span>`
                  }
                }

                that.compantList = result.data ? result.data : result
                that.companyParentList = that.compantList
                jsonarray = result.data ? result.data : result
                callback.call(this, jsonarray)
              },
              error: function (data, errorMsg) {
                if (data.statusText === 'timeout') {
                  this.jsonApiService.message('请求超时,请重试')
                } else {
                  common.clearCookie('isLogin')
                  common.clearCookie('WEBSIDE_SID')
                  localStorage.clear()
                  this.router.navigate(['/auth'])
                }
              }
            })
            // }else{
            // 	that.compantList = that.companyParentList;
            // 	for(let i = 0; i < that.companyParentList.length; i++) {
            // 		that.companyParentList[i].text = that.companyParentList[i].text + `<span style="display: none;">${pinyin(that.companyParentList[i].text,{style: pinyin.STYLE_NORMAL}).join('')}</span>`
            // 	}
            // 	callback.call(this, that.companyParentList);
            // }
          },
          themes: {
            responsive: true
          },
          multiple: false,
          animation: 100,
          dblclick_toggle: true,
          expand_selected_onload: true
        },
        plugins: ['search']
      })
      .bind('activate_node.jstree', function (e, obj) {
        var currentNode = obj.node // 获取当前节点
        currentNode.text = currentNode.text.substring(0, currentNode.text.indexOf('<')) // 获取内容前删除添加的拼音字段
        that.companyName = currentNode.text
        that.companyId = currentNode.id
        that.companyOption = currentNode.original || {}
        that.companyCode = currentNode.original.companyCode || ''
        $('#' + that.companyTreeId)
          .find('.tree_company_input')
          .val(currentNode.text)
          .change()
        $('#' + that.companyTreeId)
          .find('.treeSearchInput')
          .val('')
        that.companySearch()
        that.sendParent()
        if ($('#' + that.companyTreeId).find('.jstree-searchCheck').length > 0) {
          if (
            $('#' + that.companyTreeId).find('.jstree-searchCheck')[0].className ==
              'jstree-anchor jstree-search jstree-searchCheck' ||
            $('#' + that.companyTreeId).find('.jstree-searchCheck')[0].className ==
              'jstree-anchor jstree-searchCheck jstree-hovered jstree-clicked'
          ) {
            $('#' + that.companyTreeId).find('.s_tree_box')[0].className = 's_tree_box'
            that.selectIndex = ''
            that.selectCount = ''
          }
        } else {
          if (that.companyName) {
            $('#' + that.companyTreeId).find('.s_tree_box')[0].className = 's_tree_box'
          }
        }
      })
  }
  //擦除公司所选值
  delText() {
    this.companyName = ''
    this.companyId = ''
    $('#' + this.companyTreeId)
      .find('.treeSearchInput')
      .val('')
    $('#' + this.companyTreeId)
      .find('.tree_company_input')
      .val('')
      .change()
    this.sendParent()
    this.companySearch()
    if (
      $('#' + this.companyTreeId)
        .find('.s_tree_box')[0]
        .className.indexOf('tree_open') > 0
    ) {
      $('#' + this.companyTreeId)
        .find('.tree_company_input')
        .focus()
    }
    this.selectIndex = ''
    this.selectCount = ''
    if ($('#' + this.companyTreeId).find('.jstree-searchCheck').length != 0) {
      $('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = 'jstree-anchor'
    }
  }
  //打开公司树
  companyClick(e) {
    var treeBox = $('.s_tree_box')
    for (var i = 0; i < treeBox.length; i++) {
      if (e.target.parentNode.parentNode.parentNode.id != this.companyTreeId) {
        treeBox[i].className = treeBox[i].className.replace('tree_open', '')
      }
    }
    if (
      $('#' + this.companyTreeId)
        .find('.s_tree_box')[0]
        .className.indexOf('tree_open') < 0
    ) {
      System.import('assets/js/jstree/jstree.min.js').then(() => {
        this.initCompanyList()
        this.companyCilckEvent()
      })
    }
    $('#' + this.companyTreeId)
      .find('.s_tree_box')
      .toggleClass('tree_open')
    $('#' + this.companyTreeId)
      .find('.treeSearchInput')
      .val('')

    this.selectIndex = ''
    this.selectCount = ''
    if ($('#' + this.companyTreeId).find('.jstree-searchCheck').length != 0) {
      $('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = 'jstree-anchor'
    }
  }
  //顶级目录处理
  companyRoot() {
    this.companyName = this.companyListName
    this.companyId = ''
    $('#' + this.companyTreeId)
      .find('.tree_company_input')
      .val(this.companyListName)
      .change()
    this.sendParent()
  }
  //公司树模糊搜索
  companySearch() {
    var that = this
    var value = $('#' + this.companyTreeId).find('.treeSearchInput').val()

    that.selectIndex = ''
    that.selectCount = ''
    // for (var j = 0; j < $('#' + this.companyTreeId).find('.jstree-anchor').length; j++) {
    //   $('#' + this.companyTreeId).find('.jstree-anchor')[j].className = 'jstree-anchor'
    // }
    const oldSearchCheckElList = $('#' + this.companyTreeId).find('.jstree-searchCheck')
    if(oldSearchCheckElList.length > 0) {
      for (var j = 0; j <oldSearchCheckElList.length; j++) {
        oldSearchCheckElList[j].className = 'jstree-anchor'
      }
    }

    if (this.clearTimer) {
      clearTimeout(this.clearTimer)
    }
    this.clearTimer = setTimeout(function () {
      $('#' + that.companyTreeId)
        .find('.treeId')
        .eq(0)
        .jstree(true)
        .search(value)
      let searchResult = $('#' + that.companyTreeId).find('.jstree-search').length

      if (searchResult < 1) {
        return
      }

      if (value) {
        that.selectIndex = 1
        that.selectCount = $('#' + that.companyTreeId).find('.jstree-search').length
        $('#' + that.companyTreeId).find('.jstree-search')[0].className =
          'jstree-anchor jstree-search jstree-searchCheck'
      }

      $('#' + that.companyTreeId)
        .find('.jstree-search')
        .each(function (index, obj) {
          if (index < 1) {
            //js树搜索定位到结果的第一个地方；
            let container = $('#' + that.companyTreeId).find('.vision_tree')
            let scrollTo = $(this)
            container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130)
            container.animate({
              scrollTop:
                scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
            })
          }
        })
    }, 250)
  }
  upArrow() {
    var that = this
    if (parseInt(this.selectIndex) == 1) {
      that.jsonApiService.message('目前已经在开始位置')
      return
    }
    that.selectIndex = parseInt(that.selectIndex) - 1
    $('#' + that.companyTreeId).find('.jstree-search')[that.selectIndex - 1].className =
      'jstree-anchor jstree-search jstree-searchCheck'
    $('#' + that.companyTreeId).find('.jstree-searchCheck')[1].className = 'jstree-anchor jstree-search'

    let container = $('#' + that.companyTreeId).find('.vision_tree')
    let _this = $('#' + this.companyTreeId)
      .find('.jstree-search')
      .eq(that.selectIndex - 1)
    let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
    container.animate({ scrollTop: top })
  }
  downArrow() {
    var that = this
    if (parseInt(this.selectIndex) == parseInt(this.selectCount)) {
      that.jsonApiService.message('目前已经在结束位置')
      return
    }
    let lenindex = parseInt(this.selectIndex)
    $('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = 'jstree-anchor jstree-search '
    this.selectIndex = parseInt(this.selectIndex) + 1
    $('#' + this.companyTreeId).find('.jstree-search')[lenindex].className =
      'jstree-anchor jstree-search jstree-searchCheck'

    let container = $('#' + that.companyTreeId).find('.vision_tree')
    let _this = $('#' + this.companyTreeId)
      .find('.jstree-search')
      .eq(lenindex)
    let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
    container.animate({ scrollTop: top })
  }
  //公司树模糊搜索
  companySearchBtn() {
    var that = this
    var value = $('#' + this.companyTreeId)
      .find('.treeSearchInput')
      .val()
    $('#' + this.companyTreeId)
      .find('.treeId')
      .eq(0)
      .jstree(true)
      .search(value)
    let searchResult = $('#' + this.companyTreeId).find('.jstree-search').length
    if (searchResult < 1) {
      that.jsonApiService.message('未搜索到结果')
      return
    }
    $('#' + this.companyTreeId)
      .find('.jstree-search')
      .each(function (index, obj) {
        console.log(index, '22222222')
        if (index < 1) {
          //js树搜索定位到结果的第一个地方；
          let container = $('#' + that.companyTreeId).find('.vision_tree')
          let scrollTo = $(this)
          container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130)
          container.animate({
            scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
          })
        }
      })
  }
}
